<template>
  <main>
    <section class="publish">
      <Form>
        <Select v-model="blog.flag" style="width: 70px">
          <Option v-for="item in flag" :key="item.value" :value="item.value">{{item.label}}</Option>
        </Select>
        <Input v-model="blog.title" placeholder="请输入标题" style="width: calc(100% - 70px)"></Input>
        <mavon-editor
          v-model="blog.content"
          placeholder="编辑内容，支持 Markdown"
          class="editor"
        ></mavon-editor>
        <Cascader 
          trigger="hover" 
          :data="typeSelect" 
          v-model="currentType" 
          placeholder="分类"
          style="width: 50%" 
        ></Cascader>
        <Select v-model="blog.tagIds" multiple :max-tag-count="5" placeholder="标签" style="width: 50%">
          <Option v-for="item in tagSelect" :value="item.value" :key="item.value">{{ item.label }}</Option>
        </Select>
        <Input prefix="md-images" v-model="blog.firstPicture" placeholder="封面图片地址" style="width: 100%" class="picture"/>
        <Input show-word-limit v-model="blog.description" 
          maxlength="200"  
          type="textarea" 
          placeholder="博客描述..." 
          style="width: 100%"
        />
        <FormItem>
          <Checkbox v-model="blog.recommend">推荐</Checkbox>
          <Checkbox v-model="blog.shareStatement">转载声明</Checkbox>
          <Checkbox v-model="blog.appreciation">赞赏</Checkbox>
          <Checkbox v-model="blog.commentabled">评论</Checkbox>
          <Checkbox v-model="blog.top">置顶</Checkbox>
        </FormItem>
        <FormItem>
          <Button type="success" @click="publish(isUpdate ? 'update' : 'publish')">
            {{ isUpdate ? '更新' : '发布' }}
          </Button>
          <Button type="info" @click="publish('save')">保存</Button>
          <Button type="default" onclick="window.history.go(-1)">返回</Button>
        </FormItem>
      </Form>
    </section>
  </main>
</template>

<script>
import { mavonEditor } from 'mavon-editor'
import { 
  saveBlog,
  updateBlog,
  findBlogById,
  findTagList,
  findTypeList
} from 'service'
import { loading } from 'mixins/loading'

Vue.use(MavonEditor)

export default {
  name: 'BlogPublish',
  mixins: [loading],
  data() {
    return {
      isUpdate: false,
      flag: [
        {label:'原创', value:'原创'},
        {label: '转载', value:'转载'}, 
        {label: '翻译', value:'翻译'}
      ],
      blogId: this.$route.params.id || 0,
      blog: {
        title: '',
        content: '',
        flag: '原创',
        type: {},
        tagList: [],
        tagIds: [],
        firstPicture: '',
        description: '',
        appreciation: true,
        shareStatement: true,
        commentabled: true,
        recommend: true,
        top: false
      },
      typeSelect: [],
      tagSelect: [],
      typeList: [],
      tagList: []
    }
  },
  created() {
    if (this.blogId) {
      this.isUpdate = true
      this.getBlog()
    }
    this.getTypes()
    this.getTags()
  },
  watch: {
    $route(to, from) { 
      if (to.path.indexOf('/blog/publish') !== -1) {
        this.blog.title = ''
        this.blog.content = ''
        this.blog.description = ''
        this.blog.firstPicture = ''
        this.blog.type = {}
        this.blog.tagList = []
        this.blog.tagIds = {}
        this.isUpdate = false
      }
    }
  },
  computed: {
    currentType: {
      get() {
        return [this.blog.type.parentId || 0, this.blog.type.id || 0]
      },
      set(type) {
        return this.setType(type)
      }
    }
  },
  methods: {
    async getBlog() {
      let res = await findBlogById(this.blogId)
      this.blog = res.data.data
    },
    async getTypes() {
      let res = await findTypeList()
      var list = this.typeList = res.data.data
      var types = []
      for (var i=0; i<list.length; i++) {
        var data = {value: '', label: '', children: []}
        types.push(data)
        types[i].value = list[i].id
        types[i].label = list[i].name
        if (list[i].childTypes.length != 0) {
          for (var j=0; j<list[i].childTypes.length; j++) {
            var child = {value:'', label: ''}
            types[i].children.push(child)
            types[i].children[j].value = list[i].childTypes[j].id
            types[i].children[j].label = list[i].childTypes[j].name
          }
        }
      }
      this.typeSelect = types
    },
    async getTags() {
      let res = await findTagList(1, 0)
      var list = this.tagList = res.data.data.list
      var tags = []
      for (var i=0; i<list.length; i++) {
        var data = {value: '', label: ''}
        tags.push(data)
        tags[i].value = list[i].id
        tags[i].label = list[i].name
      }
      this.tagSelect = tags
    },
    setType(type) {
      if (type.length > 1) {
        this.blog.type.parentId = type[0]
        this.blog.type.id = type[1]
      } else {
        this.blog.type.parentId = 0
        this.blog.type.id = type[0]
      }
      this.blog.type.name = this.getTypeName(type)
    },
    getTypeName(type) {
      var name = ''
      var list = this.typeList
      list.forEach(function (item) {
        if(type[0] === item.id) {
          name = item.name
          if(type.length > 1) {
            item.childTypes.forEach(function (child) {
              if(type[1] === child.id) {
                name = child.name
              }
            })
          } 
        }
      })
      return name
    },
    updateTagAndUser() {
      this.blog.tagList = [];
      this.blog.tagList = this.tagList.filter(
        item => this.blog.tagIds.indexOf(item.id) != -1
      )
      this.blog.user = this.$store.getters['user/user']
    },
    //save update publish
    async publish(opt) {
      let validate = this.validate()
      console.log(validate)
      if(validate) {
        this.openLoading('Saving~~')
        this.updateTagAndUser()
        switch(opt) {
          case 'save': {
            this.blog.published = false
            if (this.$route.path.indexOf('/blog/edit') !== -1) {
              let res = await updateBlog(this.blog)
              if (res.data.flag) {
                this.$Message.success('博客保存成功~~')
                this.$router.push("/profile/blog/manage")
              } else {
                this.$Message.error('出错了owo，保存失败...')
              }
              this.$Spin.hide()
            } else {
              let res = await saveBlog(this.blog)
              console.log(res)
              if (res.data.flag) {
                this.$Message.success('博客保存成功~~')
                this.$router.push("/profile/blog/manage")
              } else {
                this.$Message.error('出错了owo，保存失败...')
              }
              this.$Spin.hide()
            }
            break
          }
          case 'update': {
            this.blog.published = true
            let res = await updateBlog(this.blog)
            console.log(res)
            if (res.data.flag) {
              this.$Message.success('博客更新成功~~')
              this.$router.push("/profile/blog/manage")
            } else {
              this.$Message.error('出错了owo，更新失败...')
            }
            this.$Spin.hide()
            break
          }
          case 'publish': {
            this.blog.published = true
            let res = await saveBlog(this.blog)
            if (res.data.flag) {
              this.$Message.success('博客发布成功~~')
              this.$router.push("/profile/blog/manage")
            } else {
              this.$Message.error('出错了owo，发布失败...')
            }
            this.$Spin.hide()
            break
          }
        }
      }
    },
    // 表单验证
    validate() {
      if(this.blog.title.trim() === '') {
        this.$Message.warning('先输入博客标题哦~~')
        return false
      } else if (this.blog.content.trim() === '') {
        this.$Message.warning('要写点什么呢~~')
        return false
      } else if (this.blog.type.id === 0) {
        this.$Message.warning('记得设置博客分类哦~~')
        return false
      } else if (this.blog.firstPicture.trim() === '') {
        this.$Message.warning('给博客加上好看的封面吧~~')
        return false
      } else if (this.blog.description.trim() === '') {
        this.$Message.warning('简单描述一下博客哟~~')
        return false
      }
      return true
    }
  },
}
</script>

<style lang="scss" scoped>
main {
  max-width: 1000px;
  .publish {
    padding: 1rem 0.5rem 2rem;
    .picture {
      margin: 1rem 0;
    }
  }
}
</style>
<style lang="scss">
.publish {
  .ivu-form-item {
    margin-top: 0.5rem;
  }
  .v-note-wrapper {
    margin: auto;
    z-index: 9;
    min-height: 600px;
    max-height: 100vh;
    margin: 1rem 0;
  }
  .ivu-cascader {
    display: inline-block;
  }
  .ivu-select {
    box-shadow: rgba(0,0,0,0.1) 0px 2px 12px 0px;
  }
  .ivu-input-wrapper {
    box-shadow: rgba(0,0,0,0.1) 0px 2px 12px 0px;
  } 
  .ivu-select-prefix {
    padding: 0 .2rem;
    font-size: 16px;
    color: #808695;
  }
  .ivu-checkbox {
    margin-bottom: 0.2rem;
  }
  textarea {
    height: 100px;
  }
  button.ivu-btn {
    float: right;
    margin: 0 0.2rem;
  }
}
</style>